package filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class MonFiltre
 */
public class MonFiltre implements Filter {

	/**
	 * Default constructor.
	 */
	public MonFiltre() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		//récupération de l'uri envoyée par le client
		String queryString = ((HttpServletRequest) (request)).getQueryString(); //paramètres get eventuels
		String fullClientURI = ((HttpServletRequest) (request)).getRequestURI()
				+ ((queryString != null) ? "?" + queryString : ""); //uri+paramètres get
		
		System.out.println("avt : " + fullClientURI);


		// si page de login demandée on peut faire suivre
		if (fullClientURI.endsWith("cmd=login")
				|| fullClientURI.endsWith("login.jsp")) {
			// pass the request along the filter chain
			chain.doFilter(request, response);
			return;
		}

		// sinon on vérifie la session et le login
		//récup de session si existante
		HttpSession session = ((HttpServletRequest) request).getSession(false);
		// si session nulle ou client non loggé
		if ((session == null) || session.getAttribute("login") == null) {
			//forwardvers la page de login
			((HttpServletRequest) request).getRequestDispatcher(
					"magasin?cmd=doLogin").forward(
					(HttpServletRequest) request,
					(HttpServletResponse) response);
			return;
		}

		// pass the request along the filter chain
		chain.doFilter(request, response);
		System.out.println("all ok");
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
